package comments

import (
	"database/sql"
	_ "github.com/mattn/go-sqlite3"
	"log"
	"os"
)

const (
	SafePath = "./_safe/"
	DataPath = "./_safe/data.sqlite"
	InitSql  = `
CREATE TABLE "COMMENTS" (
"ID"	INTEGER NOT NULL,
"PID"	INTEGER NOT NULL DEFAULT 0,
"DOC_ID"	VARCHAR(16) NOT NULL,
"USER_ID"	VARCHAR(16) NOT NULL,
"USER_NAME"	INTEGER NOT NULL,
"QUOTE_ID"	VARCHAR(16) NOT NULL,
"QUOTE_NAME"	INTEGER NOT NULL,
"CONTENT"	TEXT NOT NULL,
"CREATE_TIME"	TIMESTAMP NOT NULL DEFAULT (datetime('now', 'localtime')),
"AGREE_COUNT"	INTEGER NOT NULL DEFAULT 0,
"DELETED"	INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY("ID" AUTOINCREMENT)
)`
)

// 初始化
func init() {
	_, err := os.Stat(SafePath)
	if os.IsNotExist(err) {
		_ = os.MkdirAll(SafePath, os.ModeDir)
	}
	_, err = os.Stat(DataPath)
	if os.IsNotExist(err) {
		if db, err := getConn(); err == nil {
			if _, err = db.Exec(InitSql); err != nil {
				panic(err)
			}
			log.Println("Initializing the database")
		} else {
			panic(err)
		}
	}
}

func getConn() (*sql.DB, error) {
	return sql.Open("sqlite3", DataPath)
}

// 查询关联关系
func existComment(db *sql.DB, id int) bool {
	if id > 0 {
		defaultSql := "SELECT COUNT(1) FROM COMMENTS WHERE ID = ? AND DELETED = 0"
		rows, _ := db.Query(defaultSql, id)
		defer rows.Close()
		if rows.Next() {
			var count int
			_ = rows.Scan(&count)
			return count > 0
		}
	}
	return false
}

func update(db *sql.DB, updateSql string, args ...interface{}) (int, error) {
	stmt, err := db.Prepare(updateSql)
	if err != nil {
		return 0, err
	}
	res, err := stmt.Exec(args...)
	if err != nil {
		return 0, err
	}
	affect, err := res.RowsAffected()
	return int(affect), err
}
